/**
 * [30] 串联所有单词的子串
 *
 * @format
 * @lc app=leetcode.cn id=30 lang=javascript
 */

// @lc code=start
/**
 * @param {string} s
 * @param {string[]} words
 * @return {number[]}
 */
var findSubstring = function (s, words) {
    const res = []
    const LEN0 = words[0].length
    const LEN = words.length * LEN0
    // words 中所有元素都有且仅有 1 个
    function isSubString(str) {
        const dist = {}
        words.forEach(e => (dist[e] == undefined ? (dist[e] = 1) : dist[e]++))
        for (let i = 0; i < str.length; i += LEN0) {
            let key = str.slice(i, i + LEN0)
            if (dist[key] != undefined && dist[key] > 0) dist[key]--
            else return false
        }
        let flag = true
        for (let key in dist) if (dist[key] != 0) flag = false
        return flag
    }
    let i = 0
    while (i <= s.length - LEN) {
        if (isSubString(s.slice(i, i + LEN))) res.push(i)
        i++
    }
    return res
}
// debugger
// const s = "barfoothefoobarman"
// const words = ["foo", "bar"]
// const res = findSubstring(s, words)
// console.log(res)
// @lc code=end
